﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 客户管理服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class CustomersService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Customers> _customersRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public CustomersService(SqlSugarRepository<Customers> customersRep, ISqlSugarClient sqlSugarClient)
    {
        _customersRep = customersRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询客户管理 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询客户管理")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<CustomersOutput>> Page(PageCustomersInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _customersRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u =>
                u.CustomerName.Contains(input.Keyword) ||
                u.Industry.Contains(input.Keyword) ||
                u.Customersource.Contains(input.Keyword) ||
                u.ContactName.Contains(input.Keyword) ||
                u.VendorPhone.Contains(input.Keyword) ||
                u.Email.Contains(input.Keyword) ||
                u.CustomerAddr.Contains(input.Keyword) ||
                u.AccountName.Contains(input.Keyword) ||
                u.TaxCode.Contains(input.Keyword) ||
                u.BankCode.Contains(input.Keyword) ||
                u.BankOfDeposit.Contains(input.Keyword) ||
                u.BankAddr.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerName), u => u.CustomerName.Contains(input.CustomerName.Trim()))
            // ... 其他WhereIF条件保持不变 ...
            .LeftJoin<department>((u, salesDept) => u.SalesDepartments == salesDept.Id) // 使用正确的实体类
            .LeftJoin<UserInfo>((u, salesDept, director) => u.DirectorOfsales == director.Id)
            .LeftJoin<UserInfo>((u, salesDept, director, operatorUser) => u.Operator == operatorUser.Id) // 避免关键字
            .Select((u, salesDept, director, operatorUser) => new CustomersOutput
            {
                Id = u.Id,
                CustomerName = u.CustomerName,
                Industry = u.Industry,
                Customersource = u.Customersource,
                ContactName = u.ContactName,
                VendorPhone = u.VendorPhone,
                Email = u.Email,
                SalesDepartments = u.SalesDepartments,
                SalesDepartmentsFkDisplayName = salesDept.DepartmentName, // 确保属性名正确
                DirectorOfsales = u.DirectorOfsales,
                DirectorOfsalesFkDisplayName = director.UserName,
                States = u.States,
                CustomerAddr = u.CustomerAddr,
                AccountName = u.AccountName,
                TaxCode = u.TaxCode,
                BankCode = u.BankCode,
                BankOfDeposit = u.BankOfDeposit,
                BankAddr = u.BankAddr,
                Operator = u.Operator,
                OperatorFkDisplayName = operatorUser.UserName, // 使用修改后的参数名
                OperatorData = u.OperatorData,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
        return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取客户管理详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取客户管理详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Customers> Detail([FromQuery] QueryByIdCustomersInput input)
    {
        return await _customersRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加客户管理 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加客户管理")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddCustomersInput input)
    {
        var entity = input.Adapt<Customers>();
        return await _customersRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新客户管理 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新客户管理")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateCustomersInput input)
    {
        var entity = input.Adapt<Customers>();
        await _customersRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除客户管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除客户管理")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteCustomersInput input)
    {
        var entity = await _customersRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _customersRep.FakeDeleteAsync(entity);   //假删除
        //await _customersRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除客户管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除客户管理")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteCustomersInput> input)
    {
        var exp = Expressionable.Create<Customers>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _customersRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _customersRep.FakeDeleteAsync(list);   //假删除
        //return await _customersRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataCustomersInput input)
    {
        var salesDepartmentsData = await _customersRep.Context.Queryable<department>()
            .InnerJoinIF<Customers>(input.FromPage, (u, r) => u.Id == r.SalesDepartments)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.DepartmentName}"
            }).ToListAsync();
        var directorOfsalesData = await _customersRep.Context.Queryable<UserInfo>()
            .InnerJoinIF<Customers>(input.FromPage, (u, r) => u.Id == r.DirectorOfsales)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        var operatorData = await _customersRep.Context.Queryable<UserInfo>()
            .InnerJoinIF<Customers>(input.FromPage, (u, r) => u.Id == r.Operator)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "salesDepartments", salesDepartmentsData },
            { "directorOfsales", directorOfsalesData },
            { "operator", operatorData },
        };
    }
    
    /// <summary>
    /// 导出客户管理记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出客户管理记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageCustomersInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportCustomersOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "客户管理导出记录");
    }
    
    /// <summary>
    /// 下载客户管理数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载客户管理数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportCustomersOutput>(), "客户管理导入模板", (_, info) =>
        {
            if (nameof(ExportCustomersOutput.SalesDepartmentsFkDisplayName) == info.Name) return _customersRep.Context.Queryable<department>().Select(u => $"{u.DepartmentName}").Distinct().ToList();
            if (nameof(ExportCustomersOutput.DirectorOfsalesFkDisplayName) == info.Name) return _customersRep.Context.Queryable<UserInfo>().Select(u => $"{u.UserName}").Distinct().ToList();
            if (nameof(ExportCustomersOutput.OperatorFkDisplayName) == info.Name) return _customersRep.Context.Queryable<UserInfo>().Select(u => $"{u.UserName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入客户管理记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入客户管理记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportCustomersInput, Customers>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 销售部门
                    var salesDepartmentsLabelList = pageItems.Where(x => x.SalesDepartmentsFkDisplayName != null).Select(x => x.SalesDepartmentsFkDisplayName).Distinct().ToList();
                    if (salesDepartmentsLabelList.Any()) {
                        var salesDepartmentsLinkMap = _customersRep.Context.Queryable<department>().Where(u => salesDepartmentsLabelList.Contains($"{u.DepartmentName}")).ToList().ToDictionary(u => $"{u.DepartmentName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.SalesDepartments = salesDepartmentsLinkMap.GetValueOrDefault(e.SalesDepartmentsFkDisplayName ?? "");
                            if (e.SalesDepartments == null) e.Error = "销售部门链接失败";
                        });
                    }
                    // 链接 销售负责人
                    var directorOfsalesLabelList = pageItems.Where(x => x.DirectorOfsalesFkDisplayName != null).Select(x => x.DirectorOfsalesFkDisplayName).Distinct().ToList();
                    if (directorOfsalesLabelList.Any()) {
                        var directorOfsalesLinkMap = _customersRep.Context.Queryable<UserInfo>().Where(u => directorOfsalesLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.DirectorOfsales = directorOfsalesLinkMap.GetValueOrDefault(e.DirectorOfsalesFkDisplayName ?? "");
                            if (e.DirectorOfsales == null) e.Error = "销售负责人链接失败";
                        });
                    }
                    // 链接 操作人
                    var operatorLabelList = pageItems.Where(x => x.OperatorFkDisplayName != null).Select(x => x.OperatorFkDisplayName).Distinct().ToList();
                    if (operatorLabelList.Any()) {
                        var operatorLinkMap = _customersRep.Context.Queryable<UserInfo>().Where(u => operatorLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Operator = operatorLinkMap.GetValueOrDefault(e.OperatorFkDisplayName ?? "");
                            if (e.Operator == null) e.Error = "操作人链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Customers>>();
                    
                    var storageable = _customersRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.CustomerName?.Length > 32, "客户名称长度不能超过32个字符")
                        .SplitError(it => it.Item.Industry?.Length > 32, "所属行业长度不能超过32个字符")
                        .SplitError(it => it.Item.Customersource?.Length > 32, "客户来源长度不能超过32个字符")
                        .SplitError(it => it.Item.ContactName?.Length > 32, "联系人长度不能超过32个字符")
                        .SplitError(it => it.Item.VendorPhone?.Length > 32, "联系电话长度不能超过32个字符")
                        .SplitError(it => it.Item.Email?.Length > 32, "电子邮件长度不能超过32个字符")
                        .SplitError(it => it.Item.CustomerAddr?.Length > 32, "客户地址长度不能超过32个字符")
                        .SplitError(it => it.Item.AccountName?.Length > 32, "账户名称长度不能超过32个字符")
                        .SplitError(it => it.Item.TaxCode?.Length > 32, "纳税人识别号长度不能超过32个字符")
                        .SplitError(it => it.Item.BankCode?.Length > 32, "银行账户长度不能超过32个字符")
                        .SplitError(it => it.Item.BankOfDeposit?.Length > 32, "开户银行长度不能超过32个字符")
                        .SplitError(it => it.Item.BankAddr?.Length > 32, "开户行地址长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
